package com.immortal.core.module.secure.advice;

import com.immortal.core.module.secure.service.DecryptHttpDecoder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;

/**
 * <p>TODO
 *
 * @author wind
 * @version 1.0
 * @since 2018/12/19
 */
@Slf4j
public class DecryptHttpInputMessage implements HttpInputMessage {
    private HttpHeaders headers;
    private InputStream body;


    public DecryptHttpInputMessage(HttpInputMessage inputMessage, DecryptHttpDecoder decryptHttpDecoder) throws IOException {
        this.headers = inputMessage.getHeaders();
        String content = IOUtils.toString(inputMessage.getBody(), Charset.defaultCharset());
        long startTime = System.currentTimeMillis();
        // JSON 数据格式的不进行解密操作
        String decryptBody;
        if (content.trim().startsWith("{")) {
            decryptBody = content;
        } else {
            decryptBody = decryptHttpDecoder.decode(content);
        }
        long endTime = System.currentTimeMillis();
        log.debug("Decrypt Time:" + (endTime - startTime));
        this.body = IOUtils.toInputStream(decryptBody, Charset.defaultCharset());
    }

    @Override
    public InputStream getBody() {
        return body;
    }

    @Override
    public HttpHeaders getHeaders() {
        return headers;
    }
}
